import { defineConfig, loadEnv } from 'vite'
import { viteMockServe } from 'vite-plugin-mock'
import react from '@vitejs/plugin-react'
import path from 'path'

export default ({ mode }) => {
  // eslint-disable-next-line no-undef
  const env = loadEnv(mode, process.cwd());
  const { VITE_BASE, VITE_SERVER_URL } = env;

  return defineConfig({
    base: VITE_BASE,
    plugins: [
      react(),
      viteMockServe({
        mockPath: './mock', // mock文件存放目录
        enable: mode === 'test',  // 哪个环境启用mock
        watchFiles: true,
        logger: true,
        cors: true,
      })
    ],
    envPrefix: ['REACT_', 'VITE_'],
    // 开发服务器配置
    server: {
      port: 3000, // 开发服务器端口号
      open: true, // 启动时自动打开浏览器
      cors: true, // 允许跨域
      proxy: {
        // 接口请求代理
        '/gateway': {
          target: VITE_SERVER_URL,
          changeOrigin: true,
          // rewrite: (path) => path.replace(/^\/gateway/, '')，
        }
      }
    },
    // 构建配置
    build: {
      assetsDir: 'assets', // 静态资源目录
      sourcemap: false, // 是否生成 sourcemap
      rollupOptions: {
        output: {
          // 手动分包
          manualChunks: {
            react: ['react', 'react-dom'],
            vendor: ['lodash']
          }
        }
      },
    },
    // 路径别名配置
    resolve: {
      alias: {
        // eslint-disable-next-line no-undef
        '@': path.resolve(__dirname, './src')
      }
    },
    // CSS 配置
    css: {
      preprocessorOptions: {
        // 添加Less配置
        less: {
          javascriptEnabled: true
        }
      }
    }
  })
}